
/*
函数列表:
encodeHtml(s) 转义
getByteLen(str) 获取文本字节长度
insert1(text) 插入文本1 替换选中文本
insert2(text1,text2) 插入文本 包裹选中文本
log(var1) 日志;
addEditor(divid,value,title,config) 添加一个编辑器
delEditor()卸载一个编辑器
getConfig()获取编辑器配置
fullScreen(var1);切换全屏
nowEditor();返回当前正在使用的编辑器
*/



var $MY={};
$MY.lt_open = $('.lt .open');
var REGX_HTML_ENCODE = /"|&|'|<|>|[\x00-\x20]|[\x7F-\xFF]|[\u0100-\u2700]/g;
function encodeHtml(s){
return (typeof s != "string") ? s :
s.replace(REGX_HTML_ENCODE,
    function($0){
        var c = $0.charCodeAt(0), r = ["&#"];
        c = (c == 0x20) ? 0xA0 : c;
        r.push(c); r.push(";");
        return r.join("");
    });
}
function getByteLen(str){
return str.replace(/[^\x00-\xff]/gi, "--").length;
}
    /*插入文本*/
function insert1(text){
    if(nowEditor()){
        nowEditor().insert(text);
        nowEditor().focus()
    }
}
function insert2(text1,text2){
    if(nowEditor()){
        nowEditor().insert(text1+editor[editornow].session.getTextRange(editor[editornow].getSelectionRange())+text2);
        nowEditor().focus()
    }
}
function nowEditor(var1){
    if(var1!=null){
        editornow = var1;
        if(editor[var1]){
            $('.editorbox pre').removeClass('now');
            $('#editor'+var1).addClass('now');
            $('#filemenu .open li a').removeClass('now');
            $('#openlist'+var1).addClass('now');
        }
    }
    if(editornow!=null){
        return editor[editornow];
    }
    return false;
}


    

    var funmenu =[
        {name:'资源路径',
         list:[
             {name:'APP',value:'{APP_PATH}'},
             {name:'IMG',value:'{IMG_PATH}'},
             {name:'CSS',value:'{CSS_PATH}'},
             {name:'JS',value:'{JS_PATH}'}
         ]
        },
        {name:'A链接',list:[
            {name:'空',valuel:'<a href="#" title="">',valuer:'</a>'},
            {name:'列表',valuel:'<a href="{r[\'url\']}" title="{r[\'title\']}">',valuer:'</a>'}
        ]},
        {name:'注释',list:[
            {name:'/**/',valuel:'/*',valuer:'*/'},
            {name:'<!--',valuel:'<!--',valuer:'-->'},
            {name:'//',valuel:'//',valuer:''}
        ]},
        {name:'调用模板',list:[
            {name:'头部',value:'{template "content","header"}'},
            {name:'尾部',value:'{template "content","footer"}'}
        ]},
        {name:'栏目变量',list:[
            {name:'栏目ID',value:'{$catid}'},
            {name:'栏目名',value:'{$catname}'},
            {name:'栏目图片',value:'{$category_images}'},
            {name:'ID2名',value:'{$CATEGORYS[$catid][catname]}'},
            {name:'ID2图',value:'{$CATEGORYS[$catid][image]}'},
            {name:'父名',value:'{$CATEGORYS[$CAT[parentid]][catname]}'},
            {name:'父图',value:'{$CATEGORYS[$CAT[parentid]][image]}'},
            {name:'父ID',value:'{$CAT[parentid]}'},
            {name:'栏目数组',value:'{$CATEGORYS}'}
        ]},
        {name:'获取站点id',list:[
            {name:'获取站点id',value:'{siteurl($siteid)}'}
        ]},
        {name:'面包屑导航',list:[
            {name:'面包屑导航',value:'{catpos($catid)}'}
        ]},
        {name:'面包屑导航'},
        {name:'链接',list:[
            {name:'列表文字链接',value:'{$r[\'url\']}'}
        ]},
        {name:'标题',list:[
            {name:'列表',value:'{$r[\'title\']}'},
            {name:'内容',value:'{$title}'}
        ]},
        {name:'缩略图',list:[
            {name:'列表',value:'{$r[\'thumb\']}'},
            {name:'内容',value:'{$thumb}'}
        ]},
        {name:'发布时间',list:[
            {name:'列表',value:'{date(\'Y-m-d H:i:s\',$r[\'inputtime\'])}'},
            {name:'内容',value:'{$inputtime}'},
            {name:'内容格式化',value:'{date(\'Y-m-d H:i:s\',strtotime($inputtime))}'}
        ]},
        {name:'裁剪缩略图',list:[
            {name:'列表',value:'{thumb($r[\'thumb\'],100,45)}'},
            {name:'内容',value:'{thumb($thumb,100,45)}'}
        ]},
        {name:'描述',list:[
            {name:'列表',value:'{$r[\'description\']}'},
            {name:'内容',value:'{$description}'}
        ]},
        {name:'裁剪文字',list:[
            {name:'函数',value:'{str_cut(,50,\'...\')}'},
            {name:'列表标题',value:'{str_cut($r[\'title\'],50,\'..\')}'},
            {name:'列表描述',value:'{str_cut($r[\'description\'],150,\'...\')}'},
            {name:'内容标题',value:'{str_cut($title],50,\'..\')}'},
            {name:'内容描述',value:'{str_cut($description,150,\'...\')}'}
        ]}
    ];
    $(function(){
        var i_menu = '';
        for(var key in funmenu){
            var i_html = '';
            var i_w = 0;
            for(var key2 in funmenu[key]['list']){
                i_r = funmenu[key]['list'][key2];
                i_w += (getByteLen(i_r['name']));
                if(!i_r['value'])i_r['value']='';
                if(!i_r['valuel'])i_r['valuel']='';
                if(!i_r['valuer'])i_r['valuer']='';
                i_html += "<li style=\"width:"+getByteLen(i_r['name'])+"em\" valuec=\""+encodeHtml(i_r['value'])+"\" valuel=\""+encodeHtml(i_r['valuel'])+
                    "\" valuer=\""+encodeHtml(i_r['valuer'])+"\" >"+encodeHtml(i_r['name'])+"</li>";
            }
            i_menu+="<li>"+encodeHtml(funmenu[key]['name'])+'<ul style="width:'+(i_w)+'em" class="in">'+i_html+'</ul></li>';
        }
        $('.funmenu ul').html(i_menu);
        $('.funmenu ul li ul.in li').mouseup(function(){
            var valuec = $(this).attr('valuec');
            var valuel = $(this).attr('valuel');
            var valuer = $(this).attr('valuer');
            if(valuel||valuer){
                insert2(valuel,valuer);
            }else{
                insert1(valuec);
            }
        })
        $('.funmenu ul li ul.in li').mouseover(function(){
            $(this).addClass('hover');
        }).mouseout(function(){
            $(this).removeClass('hover');
        })
        
        $('.funmenu>ul>li').mousemove(function(e){
            
            var iu = $(this).find('.in');
            iu.css('transition','all 0.1s');
            var i_uw = iu.width();
            if(i_uw>=240){
//                iu.css('transition','none');
                iu.css('margin-left',0-(e.pageX/240)*(i_uw-230)+'px');
            }
        }).mouseout(function(){
            var iu = $(this).find('.in');
            iu.css('transition','all 1s');
            iu.css('margin-left',0+'px');
//            iu.css('transition','none');
        });
    })
    function log(var1){
        console.log(var1);
    }
    /*
        editor全局变量
    */
    var editor = [];
    var editornow = null;
    editornow = 0;
    /*
        添加一个新的编辑器 (eid)
        -R- : 返回数组位置
    */
    function addEditor(value,title,config){
        i_id = editor.push({})-1;
        $(".editorbox").append("<pre id='editor"+i_id+"'>");
        if(value)$('#editor'+i_id).text(value);
        editor[i_id] = ace.edit('editor'+i_id)
        config=config?config:getConfig();
        editor[i_id].setTheme(config.Theme);
        editor[i_id].session = editor[i_id].getSession();
        editor[i_id].session.setMode(config.Mode);
        editor[i_id].session.setUseWrapMode(true);
        editor[i_id].session.setTabSize(config.TabSize);
        editor[i_id].commands.removeCommand('scrollup');//卸载没用快捷键
        editor[i_id].commands.removeCommand('scrolldown');//卸载没用快捷键
        document.getElementById('editor'+i_id).style.fontSize=config.fontSize;
        if(!title)title = 'NOname '+i_id+1;
        $MY.lt_open.append('<li><a href="#" id="openlist'+i_id+'" onclick="nowEditor('+i_id+')">'+title+'</a></li>');
        nowEditor(i_id);
        return i_id;
    }
    
    /*function openEditorFocus(){
        $MY.lt_open.
    }*/
    
    /*
        销毁一个编辑器
    */
    function delEditor(eid){
         
    }
    
    
    function getConfig(){
        return {
            Theme:"ace/theme/monokai",
            Mode:"ace/mode/html",
            fontSize:'16px',
            TabSize:2
        }
    }

    function drawerOpen(var1){
        if(var1!=null){
            $('#filemenu').toggleClass('hover',var1); 
        }else{
            return $('#filemenu').hasClass('hover');
        }
        
    }
    




    /*插件系统*/
    var plugs = {};
    plugs.box = $(".plugbox");
    plugs.load = function (name){
        if(!loadJs("jsplugs/"+name+"/"+name+".js")){
            log("加载插件'"+name+"'出现错误,该插件可能无法正常工作")
        }
    }
    plugs.add = function(c,html){
        // if(!config){var config;}
        var config = arguments[2]?arguments[2]:{};
        if(!config.title){config.title=''}
        plugs.box.append("<li><a title='"+config.title+"' class='"+c+"'>"+html+"</a></a>");
        return $(".plugbox ."+c);
    }



/*cloud(ajax)系统[纯粹好看]*/
    var cloud = {}
    cloud.list = 0;
    cloud.plugtop = $(".plugtop");
    cloud.plugtopspan = $(".plugtop .cloudnum");
    cloud.uoshow=function(var1){
        if(var1<0){var1 = 0}
        cloud.plugtop.toggleClass("show",!!var1);
        if(!var1){var1='&ensp;'};
        cloud.plugtopspan.html(var1);
    }
    cloud.ajax = function(settings){
        settings.beforeSend2 = settings.beforeSend;
        settings.beforeSend = function(){
            cloud.list++;
            cloud.uoshow(cloud.list);
            settings.beforeSend2();
        }
        settings.complete2 = settings.complete;
        settings.complete = function(){
            cloud.list--;
            cloud.uoshow(cloud.list);
            settings.complete2();
        }
            $.ajax(settings);
    }
function loadJs(file){
    var ft = getUrl(file)
    if(ft){
        try{
            eval(ft);
        }
        catch(e){
            return false;
        }
    }else{
        loadJsP(file);
    }
    return true;
}

function loadJsP(resource) {
     var script = document.createElement('script');
     script.type = 'text/javascript';
     script.defer = true;
     script.text = resource;
     header.appendChild(script);
}

function loadCss(file){
    var cssTag = document.getElementById('loadCss');
    var head = document.getElementsByTagName('head').item(0);
    if(cssTag) head.removeChild(cssTag);
    css = document.createElement('link');
    css.href = file;
    css.rel = 'stylesheet';
    css.type = 'text/css';
    css.id = 'loadCss';
    head.appendChild(css);
}
function getUrl(url)
{
    var xmlHttp;
    if(window.ActiveXObject){
        xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }else if(window.XMLHttpRequest){
        xmlHttp=new XMLHttpRequest();
    }
    var chkUrl  = url;
    xmlHttp.open('get', chkUrl, false);
    try{
        xmlHttp.send();
    }
    catch(e){
        return false;
    }
    return xmlHttp.responseText;
}

function saveEditor(evt){
    log(evt);
    alert("保存!!");
    evt.stopPropagation();
    evt.preventDefault();
    return false;
}


var keyVar={shift:0,ctrl:0,alt:0};


function keyFn(evt){
    if(evt.type=="keydown"){
        if(evt.keyCode == 16){keyVar.shift=1;}
        if(evt.keyCode == 17){keyVar.ctrl=1;}
        if(evt.keyCode == 18){keyVar.alt=1;}
    }
    if(evt.type=="keyup"){
        if(evt.keyCode == 16){keyVar.shift=0;}
        if(evt.keyCode == 17){keyVar.ctrl=0;}
        if(evt.keyCode == 18){keyVar.alt=0;}
    }
// 抽屉快捷键
    if(evt.type=="keydown" && keyVar.ctrl){
        if(evt.keyCode == 38 || evt.keyCode == 40){
            if(!drawerOpen()){
                drawerOpen(true);
                $('#filemenu .open a.now').addClass('hover');
            }else{
                var openEq = $("#filemenu .open a").index($('#filemenu .open a.hover'));
                $('#filemenu .open a').removeClass('hover');
                var openEqNow = openEq;
                if(evt.keyCode == 38){openEqNow--;}else{openEqNow++;}
                log($("#filemenu .open a").length-1);
                if(openEqNow>$("#filemenu .open a").length-1){openEqNow = 0;}
                if(openEqNow==-1){openEqNow = $("#filemenu .open a").length-1}
                $("#filemenu .open li:eq("+(openEqNow)+") a").addClass('hover');
                nowEditor(openEqNow);
            }
        }
    }
    if(evt.type=="keyup" && !keyVar.ctrl){
        if(evt.keyCode == 17){
            $('#filemenu .open a').removeClass('hover');
            drawerOpen(false);
        }
    }
// 抽屉end

    if(evt.type=="keydown" && keyVar.ctrl){
        if(evt.keyCode == 83){
            saveEditor(evt);
        }
    }

}


var msg = {};
msg.list = [];
msg.add = function(text,var2,stime){
    var l_id = msg.list.push({})-1;
    msg.list[l_id].text = text; 
    msg.list[l_id].class = var2;
    $(".msg ul").prepend("<li id='msg"+l_id+"' class='"+var2+" jr'><a href='#'>"+text+"</a><span class='loading'><span class='in'></span></span></li>");
    if(stime!=-1){
        if(!stime){stime = 3;}
        msg.timeout(l_id,stime);
    }
    return l_id;
}
msg.timeout = function(l_id,stime){
    stime = Math.floor(stime);
    for (var i = 1; i <= stime; i++) {
        setTimeout("$('#msg"+l_id+" .loading .in').css('width','"+(100/stime)*i+"%');" , (i-1)*1000);
    };
    setTimeout("$('#msg"+l_id+"').removeClass('jr');" ,(stime)*1000);
    setTimeout("$('#msg"+l_id+"').detach();" ,((stime)*1000)+500);
}
msg.cutClass = function(l_id,cutClass){
    $('#msg'+l_id).removeClass('inf');
    $('#msg'+l_id).removeClass('wer');
    $('#msg'+l_id).removeClass('suc');
    $('#msg'+l_id).removeClass('err');
    $('#msg'+l_id).addClass(cutClass);
}


$(function(){
    $("html").keydown(keyFn);
    $("html").keyup(keyFn);
    //$('body').bind('keydown', 'Ctrl+s', saveEditor);
    $('#filemenu .name a').click(drawerOpen);//抽屉开关
    addEditor(document.documentElement.outerHTML);
})